Sets bits from 1 to N
Problem Statement
You are gives Q queries each query containing two integers and . Your task is to count the no of set-bits in for all numbers between and (both inclusive).
Example
Input: a = 1, b = 1
Output: 1
Input: a = 10, b = 15
Output: 17
Solution
Expected Time Complexity:
Click - to see solution
How much the bit in every number from to will contribute to the final answer?
It is equal to the number of numbers, in binary representation, having bit set. which is equal to:
&
iff
Time Complexity:
- C++
- Python
#include <bits/stdc++.h>
using namespace std;
int AllBitsOneToN(int N) {
int two = 2, ans = 0;
int n = N;
while (n) {
ans += (N / two) * (two >> 1);
int t = (N & (two - 1)) - (two >> 1) + 1;
ans += max(t, 0);
two <<= 1;
n >>= 1;
}
return ans;
}
int main() {
int q, a, b, res;
cin >> q;
while (q--) {
cin >> a >> b;
res = AllBitsOneToN(b) - AllBitsOneToN(a-1);
cout << res << "\n";
}
}
def AllbitsOneToN(N):
two = 2
ans = 0
n = N
while n:
ans += (N//two)*(two >> 1)
t = (N % two) - (two >> 1) + 1
ans += max(0, t)
two <<= 1
n >>= 1
return ans
for q in range(int(input())):
a, b = map(int, input().split())
res = AllbitsOneToN(b)
res -= AllbitsOneToN(a-1)
print(res)